package com.duanjw.springcloud.nacos.config.client.web;

import com.duanjw.springcloud.nacos.config.client.config.UserProperties;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.context.ApplicationContext;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

/**
 * nacos 配置中心客户端 controller
 * <p>
 * 注解
 * 1. @RefreshScope：动态刷新配置，作用于 @Value
 *
 * @author duanjw
 */
@RestController
@RefreshScope
public class NacosConfigClientController {

    private static final Logger log = LoggerFactory.getLogger(NacosConfigClientController.class);

    private final ApplicationContext applicationContext;
    private final UserProperties userProperties;

    @Value("${username}")
    private String username;

    public NacosConfigClientController(ApplicationContext applicationContext, UserProperties userProperties) {
        this.applicationContext = applicationContext;
        this.userProperties = userProperties;
    }

    /**
     * 通过 applicationContext.getEnvironment() 获取当前应用的配置，此值默认会自动刷新
     * <p>
     * 访问地址：curl localhost:7002/config/username
     *
     * @return
     */
    @GetMapping("config/{key}")
    public String getProperty(@PathVariable String key) {
        String property = applicationContext.getEnvironment().getProperty(key);
        log.info("property {}", property);
        return property;
    }

    /**
     * 根据 @Value 获取当前应用的配置，此值需要加 @RefreshScope 注解会自动刷新
     * <p>
     * 访问地址：curl localhost:7002/username
     *
     * @return
     */
    @GetMapping("username")
    public String getUsername() {
        log.info("username {}", username);
        return username;
    }

    /**
     * 获取通过 @ConfigurationProperties 注入的值，此值默认会自动刷新
     * <p>
     * 访问地址：curl localhost:7002/user
     *
     * @return
     */
    @GetMapping("user")
    public String getUser() {
        String user = userProperties.toString();
        log.info("user {}", user);
        return user;
    }
}